package com.liao.myblog.controller.config;

import com.liao.myblog.dao.AdminMapper;
import com.liao.myblog.pojo.Admin;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.session.Session;
import org.apache.shiro.session.mgt.SessionManager;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.SimplePrincipalCollection;
import org.apache.shiro.subject.support.DefaultSubjectContext;
import org.apache.shiro.web.mgt.DefaultWebSecurityManager;
import org.apache.shiro.web.session.mgt.DefaultWebSessionManager;
import org.apache.shiro.web.session.mgt.ServletContainerSessionManager;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Collection;

public class AdminRealm extends AuthorizingRealm {

    @Autowired
    private AdminMapper adminMapper;

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        Admin admin = (Admin) SecurityUtils.getSubject().getPrincipal();
        info.addStringPermission(admin.getPerms());
        return info;
    }

    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String username = (String) token.getPrincipal();
        Admin admin = adminMapper.adminLogin1(username);
        if (admin == null) {
            return null;
        }
        this.clearSession(admin);
        return new SimpleAuthenticationInfo(admin, admin.getPassword(), getName());
    }

    /**
     * 清空对应userName的session
     *
     * @param admin
     */
    public void clearSession(Admin admin) {
        DefaultWebSecurityManager defaultWebSecurityManager = (DefaultWebSecurityManager) SecurityUtils.getSecurityManager();
        DefaultWebSessionManager sessionManager = (DefaultWebSessionManager) defaultWebSecurityManager.getSessionManager();
        Collection<Session> sessions = sessionManager.getSessionDAO().getActiveSessions();//获取当前已登录的用户session列表
        for (Session session : sessions) {
            //清除该用户以前登录时保存的session
            SimplePrincipalCollection simplePrincipalCollection = (SimplePrincipalCollection) session.getAttribute(DefaultSubjectContext.PRINCIPALS_SESSION_KEY);
            if (null == simplePrincipalCollection) {
                continue;
            }
            Admin admin1 = (Admin) simplePrincipalCollection.getPrimaryPrincipal();
            if (admin.equals(admin1)){
                //清空对应session   清空后 被清空的用户将跳转到login界面
                session.setTimeout(0);
                sessionManager.getSessionDAO().delete(session);
                break;
            }
        }
    }
}